function u_diff=threshold_function(theta)


%%%%% Estimates the threshold value of risk-aversion at which the expected utility
%%%%% of the two lotteries would be equal

%%% The necessary variables are the money at stake in each option of each
%%% lottery (a1, b1, ..., a2, b2, ...) and the corresponding probabilites
%%% of winning each option in each lottery (p_a1, p_b1, ...)

    global a1 b1 p_a1 a2 b2 p_a2
    
    %%% The parameter to be estimated to equalize the two equations 
    w=theta;

    %%% The assumed utility function is CRRA

    %%% The two lotteries are 1 and 2 where 1 is the less risky one
    

    if w~=1
        %%% utility of option a in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_a=(a1.^(1-w))./(1-w);
        %%% utility of option b in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_b=(b1.^(1-w))./(1-w);
    else
        %%% utility of option a in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_a=log(a1);
        %%% utility of option b in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_b=log(b1);
    end
    
    %%% Expected Utility of lottery 1
    U_1_E=p_a1.*U_1_a+(1-p_a1).*U_1_b;

    if w~=1
        %%% utility of option a in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_a=(a2.^(1-w))./(1-w);
        %%% utility of option b in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_b=(b2.^(1-w))./(1-w);
    else
        %%% utility of option a in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_a=log(a2);
        %%% utility of option b in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_b=log(b2);
    end

    %%% Expected Utility of lottery 2
    U_2_E=p_a2.*U_2_a+(1-p_a2).*U_2_b;


    u_diff=U_2_E-U_1_E;

end